var fireworks = [];
var gravity;

function setup() {
    createCanvas(windowWidth, windowHeight-5).parent('box');

    gravity = createVector(0, -0.0000432 * windowHeight + 0.1261536);

    fireworks.push(new Fireworks());

    stroke(255);
    strokeWeight(4);
}

function draw() {
    background(0);

    if (random(1) < 0.08) {
        fireworks.push(new Fireworks());
        if (fireworks.length > 50) {
            fireworks.shift();
        }
    }

    for (var i = 0; i < fireworks.length; i++) {
        fireworks[i].update();
        fireworks[i].show();
    }
}

function Fireworks() {
    this.firework = new Firework(random(width), height, true, true, random(255), random(255), random(255));
    this.particles = [];

    this.update = function () {
        if (this.firework.alive) {
            this.firework.applyForce(gravity);
            this.firework.update();

            if (this.firework.vel.y >= 0) {
                this.firework.alive = false;
                this.explode();
            }
        }

        for (var i = 0; i < this.particles.length; i++) {
            this.particles[i].applyForce(gravity);
            this.particles[i].update();
        }
    };

    this.explode = function () {
        for (var i = 0; i < random(50, 80); i++) {
            this.particles.push(new Firework(this.firework.pos.x, this.firework.pos.y, false, false, random(255), random(255), random(255)));
        }
    };

    this.show = function () {
        if (this.firework.alive) {
            this.firework.show();
        }

        for (var i = 0; i < this.particles.length; i++) {
            this.particles[i].show();
        }
    };
}